package com.trytech.mongoocrawler.common.transport.protocol;

import com.trytech.mongoocrawler.common.CollectionUtils;

import java.util.List;

/**
 * 装载所有的协议解析器
 * @author jiangtao@meituan.com
 * @since: Created on 2018年04月10日
 */
public class ProtocolFilterChain {
    private static List<ProtocolHandler> handlerContainer;

    private static int index = 0;
    static {
        handlerContainer = CollectionUtils.newLinkedList();
    }

    public AbstractProtocol doFilter(AbstractProtocol protocol) throws Exception {
        ProtocolHandler protocolHandler = nextHandler();
        if(protocolHandler == null){
            throw new Exception("没有能处理信息的handler");
        }
        return protocolHandler.handle(this, protocol);
    }

    public ProtocolHandler nextHandler(){
        if(index >= handlerContainer.size()){
            return null;
        }
        return handlerContainer.get(index++);
    }

    public void addHandler(ProtocolHandler handler){
        handlerContainer.add(handler);
    }

    public void resetIndex() {
        index = 0;
    }

    public void clear() {
        handlerContainer.clear();
    }
}
